//
//  YYTabBar.swift
//  YYWeibo
//
//  Created by strongwallyi on 15/12/26.
//  Copyright © 2015年 strongwallyi. All rights reserved.
//

import UIKit

class YYTabBar: UITabBar {

    //按钮点击将会执行的闭包
    var composeButtonClickClourse:(() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(composeButton)
        backgroundImage = UIImage(named: "tabbar_background")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //布局子控件让加号按钮位于中心位置
    override func layoutSubviews() {
        //如果没有写 super 这句话,那么 tabbar 就会变成透明的
        super.layoutSubviews()
        
        composeButton.center.x = bounds.size.width * 0.5
        composeButton.center.y = bounds.size.height * 0.5
        
        //控件的宽度
        let childW = bounds.size.width * 0.2
        var index = 0
        
        //遍历子控件
        for value in subviews{
         
            //判断子控件是否为 tabbarbutton
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                value.frame.size.width = childW
                value.frame.origin.x = childW * CGFloat(index)
                index++

            }
            if index == 2 {
                index++
            }
        }
    }
    
    //按钮点击的方法,私有方法,不希望外界进行调用
    @objc private func composeButtonClick(){
        //因为闭包是一个可选值,这个地方的问号就代表,当可选值为空得时候就为 nil
        composeButtonClickClourse?()
    }

    //懒加载空间
    //private 私有,如果不想把某些属性和方法暴露给外界,就用这种方法
    private lazy var composeButton: UIButton = {
        let button = UIButton()
       
        //监听加号的点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        
        //设置不同状态的背景
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        //设置不同状态的图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        button.sizeToFit()
        
        return button
    }()
    
    
}
